package com.smartx.app.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import com.smartx.Network;
import com.smartx.app.R;
import com.smartx.app.SatApp;
import com.smartx.config.Constants;
import com.smartx.core.Wallet;
import com.smartx.crypto.Hex;
import com.smartx.crypto.Key;

import java.io.File;

public class ImportPrivateKeyFragment extends Fragment implements View.OnClickListener {

    private final static String TAG = "wallet";
    private EditText privateKey;
    private EditText password;
    private Button btnImport;

    public static ImportPrivateKeyFragment create() {
        return new ImportPrivateKeyFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return LayoutInflater.from(getContext())
                .inflate(R.layout.fragment_import_private_key, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        privateKey = view.findViewById(R.id.private_key);
        password = view.findViewById(R.id.password);
        btnImport = view.findViewById(R.id.import_action);
        btnImport.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.import_action:
                importWalletFromPrivateKey();
                break;
        }
    }

    private void importWalletFromPrivateKey(){
        privateKey.setError(null);
        String privateKey = this.privateKey.getText().toString();
        String password = this.password.getText().toString();
        if (TextUtils.isEmpty(privateKey) || privateKey.length() != 96) {
            this.privateKey.setError(getString(R.string.error_field_required));
        } else {
            //import private key and set new password
            try{
                Key key = new Key(Hex.decode(privateKey));

                //TODO: 根据是debug还是prd来决定创建MAINNET还是TESTNET
                File walletDataFile = new File(Constants.WalletDataFilePath);
                Wallet wallet = new Wallet(walletDataFile, SatApp.getInstance().getNetwork());
                createWalletWithPwd(password,key);

                //返回闪屏页，进入MainActivity
                getActivity().setResult(Activity.RESULT_OK);
                getActivity().onBackPressed();

            }catch (Exception e){
                Log.e(TAG,"import wallet from private key failed" );
                e.printStackTrace();
                //返回闪屏页
                getActivity().setResult(Activity.RESULT_CANCELED);
                getActivity().onBackPressed();
            }
        }
    }

    private void createWalletWithPwd(String password, Key key) {
        //TODO: 根据是debug还是prd来决定创建MAINNET还是TESTNET
        Wallet wallet = new Wallet(new File(Constants.WalletDataFilePath), Network.TESTNET);
        if (!wallet.unlock(password)) {
            Log.e(TAG,"create wallet failed unlock wallet failed");
            return;
        }

        if(!wallet.flush()){
            Log.e(TAG,"create wallet failed save wallet failed");
            return;
        }
        wallet.addAccount(key);

        //更新账户信息到钱包文件
        wallet.flush();

        Log.i(TAG,"create new wallet address " + key.toAddressString());
        Log.i(TAG,"create new wallet private key " + Hex.encode(key.getPrivateKey()));
        Log.i(TAG,"create new wallet public key " + Hex.encode(key.getPublicKey()));

        //设置全局的SatApp
        SatApp.getInstance().setWallet(wallet);

        //设置当前钱包使用的账户
        SatApp.getInstance().setCoinBase(0);

        //锁住钱包，以后需要的时候再unlock
        wallet.lock();
    }
}
